import React, { FC, useEffect, useState } from 'react'
import { Button, Drawer, Form, message, Radio, Select } from 'antd'
import FunGeneric from '@pages/ControllerView/components/FunctionConfig/FunGeneric'
import ProCard from '@ant-design/pro-card'
import { getFileList } from '@/services/proFile'
import { getVoPrefixAndPostfix } from '@/utils/CommUtil'
import FunReturnVo from '@pages/components/FunReturnVo'
import { updateFunction } from '@/services/function'

const FormItem = Form.Item
const formTailLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 15 }
}

interface FunRetTypeProps {
  projectId:string,
  onClose:any,
  visible:boolean,
  funDetail:any,
}

const FunRetType: FC<FunRetTypeProps> = (props) => {

  const [form] = Form.useForm()
  const { projectId, onClose, visible, funDetail } = props
  const [typeVisible, setTypeVisible] = useState<boolean>(false)
  const [voList, setVoList] = useState<any>([])
  const [resObj, setResObj] = useState<any>({})
  const [clickObj,setClickObj] = useState<any>({})
  const [parentVo,setParentVo] = useState<any>({})

  useEffect(() => {
    // 获取Vo字段列表
    if (visible) {
      getFileList({ project_id: projectId, file_type: 'vo' }).then(res => {
        if (res.code === 10000) {
          setVoList(res.data)
        }
      })
    }
  }, [projectId, visible])

  useEffect(() => {
    if (!funDetail.return_vo) return;
    let obj = JSON.parse(funDetail.return_vo)
    setResObj(obj || {})
    form.resetFields()
  }, [funDetail,visible])

  const changeTypeVisible = (flag: boolean) => {
    setTypeVisible(flag)
  }

  const callBack = (_parentVo:any, _clickObj:any) => {
    setParentVo(_parentVo)
    setClickObj(_clickObj);
    setTypeVisible(true);
  }

  const typeSubmit = (val:any) => {

    let obj = parentVo;
    while (obj.next) {
      obj = obj.next
    }

    obj.next = val

    setResObj(parentVo.next)
    setTypeVisible(false);
  }

  const submit = () => {

    const getVoShow = (_resObj:any) => {

      let {prefix, postfix} = getVoPrefixAndPostfix(_resObj)

      let name = prefix + (_resObj.name ? _resObj.name : '') + postfix
      if (_resObj.next || _resObj.paradigm == 'yes') {
        name = name + '<' + getVoShow(_resObj.next) + '>';
      }
      return name;
    }


    form.validateFields().then((res:any) => {
      const data:any = res;
      data.id = funDetail.id;
      if (data.res_type == 'vo') {
        let returnShow = getVoShow(resObj);

        let newArray = voList.filter((item:any) => item.id == data.res_vo_id)[0];
        if (newArray.paradigm === 'yes') {
          let {prefix, postfix} = getVoPrefixAndPostfix(newArray)
          data.return_show = newArray.name + '<' + prefix + returnShow + postfix + '>';
          data.return_vo = JSON.stringify(resObj);
        }else {
          data.return_vo = JSON.stringify({});
          data.return_show = newArray.name
        }

      } else {
        data.return_show = data.res_type;
      }

      updateFunction(data).then(res => {
        if (res.code === 10000) {
          message.success('保存成功');
          onClose(false);
        }
      })

    })
  }

  const voFlag = form.getFieldValue('res_type') === 'vo'
  const genericFlag = voList.filter((val: any) => val.id == form.getFieldValue('res_vo_id'))[0]?.paradigm == 'yes'

  return (
    <>
      <Drawer
        title="返回类型"
        width={800}
        onClose={() => onClose(false)}
        visible={visible}
        bodyStyle={{ paddingBottom: 80, backgroundColor: '#f0f2f5' }}
        footer={
          <div style={{
            textAlign: 'right'
          }}>
            <Button key="submit" onClick={submit} type="primary">
              保存
            </Button>
            <Button style={{ marginLeft: 10 }} onClick={() => onClose(false)}>
              关闭
            </Button>
          </div>
        }>
        <ProCard>
          <Form form={form} initialValues={funDetail}>
            <FormItem {...formTailLayout} name="res_type" rules={[{ required: true, message: '请选择对象类型' }]} label="对象类型">
              <Radio.Group>
                <Radio.Button value="void">void</Radio.Button>
                <Radio.Button value="vo">vo</Radio.Button>
                <Radio.Button value="string">string</Radio.Button>
                <Radio.Button value="file">file</Radio.Button>
                <Radio.Button value="image">image</Radio.Button>
              </Radio.Group>
            </FormItem>
            {voFlag && (
              <FormItem {...formTailLayout} name='res_vo_id' rules={[{ required: true, message: '请选择Vo对象' }]}
                        label="Vo对象">
                <Select placeholder="请选择Vo对象" style={{ width: '80%' }}>
                  {voList.map((item: any) => (
                    <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                  ))}
                </Select>
              </FormItem>
            )}
            {voFlag && genericFlag && (
              <FormItem {...formTailLayout} name="return_vo" rules={[{ required: false, message: '请选择T类型' },{
                validator: (rule, value, callback) => {
                  if (!resObj?.name) {
                    callback('请选择T类型');
                  }else {
                    callback();
                  }
                },
              },]}
                        label="T类型">
                <FunReturnVo parentVo={{}} resObj={resObj} onSelectVo={callBack} />
              </FormItem>
            )}
          </Form>
        </ProCard>
      </Drawer>
      <FunGeneric onSubmit={typeSubmit} clickObj={clickObj} voList={voList} funDetail={funDetail} onClose={changeTypeVisible} visible={typeVisible}/>
    </>
  )
}

export default FunRetType
